package rs.udd.service;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import rs.udd.model.Advertiser;
import rs.udd.model.AdvertiserAgentContact;
import rs.udd.model.Agent;
import rs.udd.repository.AdvertiserAgentContactRepository;
import rs.udd.repository.AdvertiserRepository;
import rs.udd.repository.AgentRepository;
import rs.udd.service.dto.advertiser.ContactAgentDto;
import rs.udd.service.util.SecurityUtil;

@Service
@Transactional
public class ContactAgentServiceImpl implements ContactAgentService {

	private static final Logger LOGGER = LogManager.getLogger(ContactAgentServiceImpl.class);
	
	@Resource
	private AdvertiserRepository advertiserRepository;
	
	@Resource
	private AgentRepository agentRepository;

	@Resource
	private MailService mailService;
	
	@Resource
	private AdvertiserAgentContactRepository advertiserAgentContactRepository;
	
	@Override
	public void contact(String agentUsername, ContactAgentDto contactAgentDto) {
		Agent agent = agentRepository.findByUsername(agentUsername);
		Advertiser loggedAdvertiser = SecurityUtil.getLoggedUser(Advertiser.class);
		loggedAdvertiser = advertiserRepository.findOne(loggedAdvertiser.getId());
		
		AdvertiserAgentContact contact = new AdvertiserAgentContact();
		contact.setAgent(agent);
		contact.setAdvertiser(loggedAdvertiser);
		contact.setMessage(contactAgentDto.getMessage());
		advertiserAgentContactRepository.save(contact);
		advertiserRepository.save(loggedAdvertiser);
		agentRepository.save(agent);
		
		LOGGER.info("Advertiser '" + loggedAdvertiser.getUsername() + " contacted agent '" + agent.getUsername() + "'");
		
		String sendEmailTo = agent.getEmail();
		String subject = "Advertiser contacted you";
		String body = "Advertiser " + loggedAdvertiser.getFirstname() + " " + loggedAdvertiser.getLastname() + 
				" contacted you";
		body += "\nMessage from advertiser:\n" + contactAgentDto.getMessage();
		mailService.sendMail(sendEmailTo, subject, body);
	}

	@Override
	public boolean checkIfAgentContacted(Long agentId) {
		boolean advertiserIsLogged = SecurityUtil.checkLoggedRole(Advertiser.class);
		if (advertiserIsLogged) {
			Agent agent = agentRepository.findOne(agentId);
			Advertiser advertiser = SecurityUtil.getLoggedUser(Advertiser.class);
			advertiser = advertiserRepository.findOne(advertiser.getId());
			
			AdvertiserAgentContact agentContact = advertiserAgentContactRepository.findByAdvertiserAndAgent(advertiser, agent);
			boolean contacted = advertiser.getContactedAgents().contains(agentContact);
			
			return contacted;
		} else {
			return false;
		}
	}

}
